/*
 * Created by Gibbs on 2021/1/1.
 * Copyright (c) 2021 Gibbs. All rights reserved.
 */

#include <base/Log.h>
#include <thread>
#include <base/LoopThread.h>
#include <source/Source.h>
#include "SurfaceVideoRenderer.h"
#include "Renderer.h"

SurfaceVideoRenderer::SurfaceVideoRenderer(FrameSource *source) {
    LOGI("VideoRenderer", "CoreFlow : new SurfaceVideoRenderer");
    frameSource = source;
}

SurfaceVideoRenderer::~SurfaceVideoRenderer() = default;

void SurfaceVideoRenderer::surfaceCreated(ANativeWindow *window, int videoWidth, int videoHeight) {

}

void SurfaceVideoRenderer::surfaceChanged(int width, int height) {

}

void SurfaceVideoRenderer::surfaceDestroyed() {

}

uint64_t SurfaceVideoRenderer::render(uint64_t nowMs) {
    MediaData *mediaData;
    unsigned long error = frameSource->readVidFrame(&mediaData);
    if (error == SOURCE_ERROR) {
        LOGI("SurfaceVideoRenderer", "the video queue is quit");
        return RENDER_ERROR;
    } else if (error == SOURCE_EMPTY) {
        std::this_thread::sleep_for(std::chrono::milliseconds(5));
        return RENDER_RETRY;
    } else if (error == SOURCE_END) {
        LOGI("SurfaceVideoRenderer", "the video queue is end");
        return RENDER_END;
    }
    if (nowMs > mediaData->pts) {
        frameSource->popVidFrame(mediaData);
        // 避免与RENDER_XXX错误码重合
        return (mediaData->pts < 10) ? 10 : mediaData->pts;
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(5));
    return RENDER_RETRY;
}
